package cn.kent.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class RabbitConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    private static final Logger logger = LoggerFactory.getLogger(RabbitConfig.class);
    public static final String MSG_QUEUE_NAME = "msg_queue_name";
    public static final String MSG_EXCHANGE_NAME = "msg_exchange_name";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setReturnCallback(this);
        rabbitTemplate.setConfirmCallback(this);
    }

    @Bean
    Queue msgQueue() {
        return new Queue(MSG_QUEUE_NAME, true, false, false);
    }

    @Bean
    DirectExchange msgExchange() {
        return new DirectExchange(MSG_EXCHANGE_NAME, true, false);
    }

    @Bean
    Binding msgBinding() {
        return BindingBuilder.bind(msgQueue())
                .to(msgExchange())
                .with(MSG_QUEUE_NAME);
    }

    /**
     * 消息成功到达交换机的回调
     * 消息成功到达交换机，会触发该方法
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            // 消息成功到达交换机
            logger.info("{} 消息到达交换机", correlationData.getId());
        } else {
            logger.error("{} 消息未到达交换机 {}", correlationData.getId(), cause);
        }
    }

    /**
     * 消息没有到达队列的回调
     * 消息未成功到达队列，会触发该方法
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        logger.error("{} 消息未到达队列", message.getMessageProperties().getMessageId());
    }
}
